package com.mikey.pc;

/**
 * @author :Mikey
 * @description :线程之间的通信问题：生产者和消费者问题  等待唤醒，通知唤醒
 * 线程交替执行 A,B 操作同一个变量 num=0
 * A:num+1
 * B:num+1
 * @create :2022-09-20 11:49:00
 */
public class A {
    public static void main(String[] args) {
        Date date = new Date();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    date.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    date.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
    }
}
//判断等待，业务，通知
class Date {//资源类
    private int num = 0;
    public synchronized void increment() throws InterruptedException {
        if (num != 0) {
            this.wait();
            //等待
        }
        num++;
        System.out.println(Thread.currentThread().getName()+"->"+num);
        this.notifyAll();
       //        通知其他线程，完毕
    }
    public synchronized void decrement() throws InterruptedException {
        if (num == 0) {
            this.wait();
//等待
        }
        num--;
        System.out.println(Thread.currentThread().getName()+"->"+num);
        this.notifyAll();
        //        通知其他线程，完毕
    }
}
